const path = require('path');
const fs = require('fs');
const Image = require('../models/Image');

exports.uploadImage = async (ctx) => {
  const file = ctx.request.files?.file; // 前端字段名为 "file"
  console.log(ctx.request.files);
  if (!file) {
    ctx.status = 400;
    ctx.body = { error: 'No file uploaded' };
    return;
  }

  try {
    // 创建数据库记录
    const image = await Image.create({
      // filename: file.newFilename, // koa-body 重命名后的文件名
      filename: file.originalFilename, // koa-body 重命名后的文件名
      path: path.join(__dirname, '../uploads', file.originalFilename),
      mimetype: file.mimetype,
      size: file.size
    });

    console.log();
    console.log();
    console.log(file.filepath);
    console.log(path.join(__dirname, './uploads', file.originalFilename));
    console.log(file.originalFilename);


    fs.renameSync(file.filepath, path.join(__dirname, '../uploads', file.originalFilename));


    ctx.status = 201;
    ctx.body = {
      message: 'File uploaded successfully',
      id: image.id,
      url: `http://${ctx.host}/images/${image.id}`
    };
  } catch (error) {
    // 出错时删除已上传的文件
    fs.unlinkSync(file.filepath);
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
  }
};

exports.getImage = async (ctx) => {
  const { id } = ctx.params;
  
  try {
    const image = await Image.findByPk(id);
    if (!image) {
      ctx.status = 404;
      ctx.body = { error: 'Image not found' };
      return;
    }

    ctx.type = image.mimetype;
    ctx.body = fs.createReadStream(image.path);
  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
  }
};

exports.delImage = async (ctx) => {
  const { id } = ctx.params;
  
  try {
    const image = await Image.findByPk(id);
    if (!image) {
      ctx.status = 404;
      ctx.body = { error: 'Image not found' };
      return;
    }

    await image.destroy();
    fs.unlinkSync(image.path);

    ctx.status = 200;
    ctx.body = {
      code: 200,
      message: '删除成功'
    };

  } catch (error) {
    ctx.status = 500;
    ctx.body = { error: 'Internal server error' };
  }
};


exports.getImageList = async (ctx) => {




  try {

    // 获取分页参数 (默认第1页，每页10条)
    const page = parseInt(ctx.query.page) || 1;
    const pageSize = parseInt(ctx.query.pageSize) || 10;
    
    // 计算偏移量
    const offset = (page - 1) * pageSize;

    const { count, rows } = await Image.findAndCountAll({
     offset,
     limit: pageSize,
     order: [['createdAt', 'DESC']] // 按创建时间倒序
   });
   ctx.body = {
     code: 200,
     message: '获取列表成功',
     data: rows,
     total: count
   };
 } catch (error) {
   ctx.status = 500;
   ctx.body = {
     code: 500,
     message: '服务器内部错误',
     error: error.message
   };
 }


};